from flask import Blueprint,request,jsonify
from app import cache
from app.models import Blog,Reply

api = Blueprint('api', __name__)

# 获取博文列表
@api.route('/details/by/page')
@cache.cached(timeout=60 * 60 * 24 * 100, key_prefix=make_cache_key)
def blogByPage():
    """
            @api {get} /details/by/page 获取博文列表
            @apiVersion 1.0.0
            @apiName blog_by_page
            @apiGroup Blog
            @apiParam {int}  page      (必须)    页数
            @apiParam {int}  category    (必须)    类别
            @apiParam {int}  limit    (必须)    每页记录数
            @apiParamExample {json} Request-Example:
                {
                    page: 1,
                    category: 0,
                    limit: 20
                }

            @apiSuccess (回参) {int} status  状态值
            @apiSuccess (回参) {int} Id  博文Id
            @apiSuccess (回参) {String} title  标题
            @apiSuccess (回参) {String} imgSrc  用户头像地址
            @apiSuccess (回参) {String} categoryName  分类名
            @apiSuccess (回参) {String} content  文章内容
            @apiSuccess (回参) {int} blog_count  博文总量
            @apiSuccess (回参) {String} msg  信息
            @apiSuccessExample {json} Success-Response:
                {
                    "status":1,
                    "msg":"查询成功！",
                    "data": {
                        "Id": 1,
                        "title": "标题",
                        "imgSrc": "/static/img/1/jpg",
                        "categoryName": "分类名",
                        "content": "博文内容"
                    },
                    "blog_count":100
                }

            @apiErrorExample {json} Error-Response:
                {
                    "status":0,
                    "msg""数据库查询错误！"
                }

            """
    returnData = {'status': 0}
    try:
        page = request.args.get('page', 0)
        category = request.args.get('category', 0)
        limit = request.args.get('limit', 10)
        blog_query = Blog.query
        if category and category != '0' and category != 0:
            blog_query = blog_query.filter_by(categoryid=category)
        blogList = blog_query.order_by(Blog.createTime.desc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': one.id, 'title': one.title, 'imgSrc': one.imgSrc,
             'categoryName': one.categoryInfo.name,
             'content': '。'.join(html_to_plain_text(one.content).strip().split('\n')[:2])} for one in blogList]
        returnData['blog_count'] = blog_query.count()
    except Exception as e:
        returnData['status'] = 1
        returnData['msg'] = '数据异常' + str(e)
    return jsonify(returnData)


# 获取评论
@api.route('/get/reply/<int:Id>')
@cache.cached(timeout=60 * 60 * 24 * 100, key_prefix=make_cache_key)
def get_reply(Id):
    """
        @api {get} /get/reply/<int:Id> 获取博文的评论
        @apiVersion 1.0.0
        @apiName get_reply
        @apiGroup Blog
        @apiParam {int}  page      (必须)    页数
        @apiParam {int}  limit    (必须)    每页记录数
        @apiParam {int}  Id    (必须)    博文Id
        @apiParamExample {json} Request-Example:
            {
                page: 1,
                limit: 20
            }

        @apiSuccess (回参) {int} status  状态值
        @apiSuccess (回参) {int} Id  博客Id
        @apiSuccess (回参) {String} title  标题
        @apiSuccess (回参) {String} nickname  昵称
        @apiSuccess (回参) {String} createTime  发布时间
        @apiSuccess (回参) {String} content  评论内容
        @apiSuccess (回参) {String} msg  信息
        @apiSuccessExample {json} Success-Response:
            {
                "status":1,
                "msg":"查询成功！",
                "data": {
                    "Id": 1,
                    "nickname": "昵称",
                    "createTime": "20211202",
                    "content": "评论内容"
                }
            }

        @apiErrorExample {json} Error-Response:
            {
                "status":0,
                "msg""数据库查询错误！"
            }

    """
    returnData = {'status': 0}
    try:
        page = request.args.get('page', 1)
        limit = request.args.get('limit', 10)
        replies = Reply.query.filter_by(blogid=Id).order_by(Reply.createtime.desc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': reply.id, 'nickname': reply.nickname,
             'createTime': reply.createtime.strftime('%Y/%m/%d'),
             'content': reply.content} for reply in replies]
        returnData['count'] = Reply.query.count()
    except Exception as e:
        returnData['status'] = 1
        returnData['msg'] = '数据异常' + str(e)
    return jsonify(returnData)